代码“中间地带”的封装与复用

原创|其它|编辑:郝浩|2009-10-15 10:01:42.000|阅读 503 次

概述:作为一个框架提供商,微软公司为我们提供了最基础最常用的类和方法,在实际工作中,我们需要去继承去组合这些类与方法,形成我们的解决方案。

# 界面/图表报表/文档/IDE等千款热门软控件火热销售中 >>

先提出一个词:中间地带。

作为一个框架提供商,微软公司为我们提供了最基础最常用的类和方法,在实际工作中,我们需要去继承去组合这些类与方法,形成我们的解决方案。
那么,存在一个问题,为什么微软公司不为我们提供一个无所不包无所不能点一下鼠标就会出现的万能代码库呢?
因为……不现实。
有一个控件Root,A需要这个类具备的功能列表假设为F(A),B需要这个类具备的功能列表为F(B),……,Z需要这个类具备的功能列表为F(Z)。
一个万能的解决方案是为这个控件实现F(God)=F(A)UF(B)UF(C)……UF(Z)这么多功能。而实际上,框架提供给我们的只有F(Root)=F(A)∩F(B) ∩F(C)……∩F(Z)这么少的功能。
对A来说,在F(Root)和F(A)之间,就存在一大片中间地带:F(Root)-F(A),如下图中的阴影部分。

 

 

 

这个中间地带(阴影部分),就是我们的舞台。

本文重点谈谈中间地带的复用。

一、扩展方法

中间地带中的代码复用有很多种方法。

最直观的是继承。继承一个类,为它加上我们希望而微软又没有提供给我们的行为。再回到中间地带那张图,我们可以得出这个结论:

所有的类都是不完备的,因为F(God)!=F(Root)

不过,对于A来说,我们不需要考虑F(God),只需要考虑F(A),为这个类补上F(A)-F(Root)之间的部分就可以了。

一个Bitmap类,我们希望这个类中有这样一个方法:

void DrawPoint(Color color, int x, int y)

 这个方法不能抛出异常(不然就太难用了),当x,y超越了索引就啥都不画。

使用继承的话,我们就要产生一个新类:XXXBitmap。怎么看怎么别扭,因为这个方法理应是 Bitmap 应该具备的行为。

现在,我们有了扩展方法。一切变得自然:

 

        public static void DrawPoint(this Bitmap map, Color color, int x, int y)
        {
            
if (x < 0 || y < 0 || x >= map.Width || y >= map.Height) return;
            map.SetPixel(x, y, color);
        }


这个例子比较简单,下面,来一个略微复杂的例子。

在Winform程序中,一个窗体或一个独立的线程T调用另一个窗体F中的方法Foo(),这个Foo()会牵扯到UI操作。这里就需要做很多事情。

首先,需要判断F是否已经关闭(F.IsHandleCreated == true)
然后,如果F未关闭,则把Foo()方法封装成一个代理WrapperOfFoo,再调用F.Invoke(WrapperOfFoo),把这个代理塞给F所在线程
最后,当F线程执行Foo()方法时,在Foo()方法的内部还需要再判断一下F是否已经关闭。

非常繁琐,一不小心就会因遗漏而出错。

下面,我们来设计扩展方法,封装上面的调用逻辑。

扩展方法的原型为:
InvokeFunc0(Func0 func0)
InvokeFunc1<T>(Func1<T> func1, T obj)
InvokeFunc2<T0, T1>(Func2<T0, T1> func2, T0 obj0, T1 obj1)

Func0,Func1,Func2是我自定义的几个delegate,因为.Net 2.0下没有Func。

下面是Func0,Func1,Func2的原型:

 public delegate void Func0();
 public delegate void Func1<T>(T obj);
 public delegate void Func2<T0,T1>(T0 obj0,T1 obj1);

设计这个扩展方法需要使用一点点小技巧。

我们用一个类ControlFuncContext来封装Foo()方法的运行时环境:


    public class ControlFuncContext
    {
        
public Control Control { getprivate set; }
        
public Delegate Delegate { getprivate set; }

        
public ControlFuncContext(Control ctl, Delegate d)
        {
            
this.Control = ctl;
            
this.Delegate = d;
        }

        
public void Invoke0()
        {
            
if (Control.IsHandleCreated == true)
            {
                Delegate.DynamicInvoke();
            }
        }

        
public void Invoke1<T>(T obj)
        {
            
if (Control.IsHandleCreated == true)
            {
                Delegate.DynamicInvoke(obj);
            }
        }

        
public void Invoke2<T0,T1>(T0 obj0, T1 obj1)
        {
            
if (Control.IsHandleCreated == true)
            {
                Delegate.DynamicInvoke(obj0, obj1);
            }
        }
    }


有了这个类,扩展方法就非常好写了:


        public static void InvokeFunc0(this Control ctl, Func0 func0)
        {
            
if (ctl.IsHandleCreated == true)
            {
                ControlFuncContext fc 
= new ControlFuncContext(ctl, func0);
                ctl.Invoke(
new Func0(fc.Invoke0));
            }
        }

        
public static void InvokeFunc1<T>(this Control ctl, Func1<T> func1, T obj)
        {
            
if (ctl.IsHandleCreated == true)
            {
                ControlFuncContext fc 
= new ControlFuncContext(ctl, func1);
                ctl.Invoke(
new Func1<T>(fc.Invoke1<T>), obj);
            }
        }

        
public static void InvokeFunc2<T0, T1>(this Control ctl, Func2<T0, T1> func2, T0 obj0, T1 obj1)
        {
            
if (ctl.IsHandleCreated == true)
            {
                ControlFuncContext fc 
= new ControlFuncContext(ctl, func2);
                ctl.Invoke(
new Func2<T0,T1>(fc.Invoke2<T0,T1>), obj0, obj1);
            }
        }


扩展方法是一个好东西。下面是俺常干的事情。

(1) 把多语言切换封装成扩展方法。

俺给Object加了一个扩展方法:String GetLabel(String key, String defaultValue). 该方法自动从俺自定义的资源文件中寻找key所对应的字符串,找到了则返回,找不到则返回defaultValue。

(2) 把一些常用的UI逻辑封装成扩展方法。

比如,删除时进行确认,并判断有没有选中项:



        
public static Boolean ShowEnsureDelMsgBox(this Control ctl)
        {
            
return MessageBox.Show(ctl.GetLabel("ConfirmDelete","确认删除?"),ctl.GetLabel("Warning","警告"), MessageBoxButtons.YesNo) == DialogResult.Yes;
        }

        
public static Boolean ShowWarningEmptyListMsgBoxAndEnsureDelMsgBox<T>(this Control ctl, ICollection<T> dels)
        {
            
if (dels == null || dels.Count == 0)
            {
                MessageBox.Show(ctl.GetLabel(
"NoSeleted""没有选中项."));
                
return false;
            }

            
return ctl.ShowEnsureDelMsgBox();
        }


获取DataGridView选中的项:

 


        public static List<T> GetSelectedItems<T>(this DataGridView dgv)
        {
            List
<T> selects = new List<T>();
            
foreach (DataGridViewRow row in dgv.SelectedRows)
            {
                T t 
= (T)row.DataBoundItem;
                selects.Add(t);
            }
            
return selects;
        }


(3) 将控件的默认值或默认行为设置几个自己常用的方案。这样,开发UI时,直接通过扩展方法选择相应的方案,而不是手动的一个个从VS的属性窗口去寻找,去一个个去调(很容易遗漏):

 


        public static void UseDefaultMode00(this DataGridView dgv)
        {
            dgv.SelectionMode 
= DataGridViewSelectionMode.FullRowSelect;
            dgv.AllowUserToAddRows 
= false;
            dgv.AllowUserToDeleteRows 
= false;
            dgv.AllowUserToOrderColumns 
= false;
            dgv.AllowUserToResizeRows 
= false;
            dgv.AutoSizeColumnsMode 
= DataGridViewAutoSizeColumnsMode.Fill;
            dgv.BackgroundColor 
= System.Drawing.Color.White;
            dgv.RowHeadersVisible 
= false;
        }


二、Mediator 模式


另一种复用策略是组合。
经常会遇到这样的情况:一个窗体或一个页面上有几个控件A、B、C,这A、B、C之间存在某种固定的行为模式。
直观上的考虑是使用用户控件。

使用用户控件有几个缺点:
(1) UI死板,难以调整
(2) Bug多(WebForm还好,WinForm自定义控件一复杂,VS就难以正确的渲染)
(3) 用户控件不是正交的,没法进一步组合。

那么,怎么办呢?
天空一声巨响,Mediator闪亮登场。

不得不承认,我以前小看了Mediator模式,将它打为二类设计模式(Strategy,Obverser,Facade是俺心中的一类设计模式,在俺心中,一类设计模式之外的模式都是渣。这里再挑衅一句:全部工厂模式都是渣。)
Mediator模式是对多个对象之间行为的抽象。关于这个模式,就只说这一句话,也没有UML图(对于俺这种程序员来说,UML就是渣一般的存在)。

下面举个例子,使用Mediator 对中间地带行为进行封装。

这个例子涉及到三个控件之间的联动:
有一个ComboBox控件显示类别列表,一个ListBox控件显示选中类别的子项列表,一个TextBox控件显示选中子项的简单介绍。然后,当双击某子项时,则自动选中该子项(遗憾的是,ListBox并不支持双击某子项的事件,得自己实现该逻辑)。

 


下面,用Mediator来实现对这一行为模式的复用。

 

先定义一个类CategoryItem。代表类别或子项。

 


    public class CategoryItem
    {
        
public String Name { getset; }
        
public String Category { getset; }
        
public String Introduce { getset; }
        
public Object Value { getset; }
        
public CategoryItem()
        {
            Name 
= Category = Introduce = String.Empty;
        }
    }


然后,写一个 CategoryItemSelectorMediator(似乎叫CategoryItemSelectMediator更恰当)


    public class CategoryItemSelectorMediator
    {
        
protected List<CategoryItem> Items { getset; }
        
protected ListBox BindedListBox { getset; }
        
protected ComboBox BindedComboBox { getset; }
        
protected TextBox BindedTextBox { getset; }

        
public CategoryItemSelectorMediator()
        {
            Items 
= new List<CategoryItem>();
        }

        
public event EventHandler<EventArgs> ListBoxItemDoubleClick;

        
protected virtual void OnListBoxItemDoubleClick(EventArgs e)
        {
            EventHandler
<EventArgs> handler = ListBoxItemDoubleClick;
            
if (handler != null)
            {
                handler(
this, e);
            }
        }

        
public void Bind(IEnumerable<CategoryItem> items, ComboBox comboBox, ListBox listBox, TextBox txtBox)
        {
            
if (items == nullthrow new ArgumentNullException("items");
            
if (comboBox == nullthrow new ArgumentNullException("comboBox");
            
if (listBox == nullthrow new ArgumentNullException("listBox");
            
if (txtBox == nullthrow new ArgumentNullException("txtBox");

            
this.Items.Clear();
            
this.Items.AddRange(items);
            
this.BindedComboBox = comboBox;
            
this.BindedListBox = listBox;
            
this.BindedTextBox = txtBox;
            
this.BindedComboBox.SelectedIndexChanged += new EventHandler(BindedComboBox_SelectedIndexChanged);
            
this.BindedListBox.SelectedIndexChanged += new EventHandler(BindedListBox_SelectedIndexChanged);
            
this.BindedListBox.MouseDoubleClick += new MouseEventHandler(BindedListBox_MouseDoubleClick);
            
this.BindedComboBox.DataSource = this.GetCategorys();
            BindListBox(
"全部");
        }

        
private void BindedListBox_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            
int itemRegionHeight = this.BindedListBox.Items.Count * this.BindedListBox.ItemHeight;
            
if (e.Y <= itemRegionHeight)
            {
                OnListBoxItemDoubleClick(EventArgs.Empty);
            }
        }

        
private void BindListBox(String category)
        {
            
this.BindedListBox.DataSource = this.Find(category);
            
this.BindedListBox.DisplayMember = "Name";
        }

        
private List<String> GetCategorys()
        {
            List
<String> categorys = new List<string>();
            categorys.Add(
"全部");
            
foreach (var item in Items)
            {
                Boolean find 
= false;
                
foreach (var c in categorys)
                {
                    
if (c == item.Category)
                    {
                        find 
= true;
                        
break;
                    }
                }
                
if (find == false) categorys.Add(item.Category);
            }
            
return categorys;
        }

        
private List<CategoryItem> Find(String categoryName)
        {
            
if (categoryName == "全部"return this.Items;
            
else
            {
                List
<CategoryItem> finds = new List<CategoryItem>();
                
foreach (var item in this.Items)
                {
                    
if (item.Category == categoryName) finds.Add(item);
                }
                
return finds;
            }
        }

        
private void BindedComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            
this.BindListBox(this.BindedComboBox.Text);
        }

        
private void BindedListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            Object obj 
= this.BindedListBox.SelectedItem;
            
if (obj == nullthis.BindedTextBox.Text = String.Empty;
            
else
            {
                CategoryItem item 
= obj as CategoryItem;
                
this.BindedTextBox.Text = item.Introduce;
            }
        }

        
public List<CategoryItem> SelectItems
        {
            
get
            {
                List
<CategoryItem> list = new List<CategoryItem>(this.BindedListBox.SelectedItems.Count);
                
foreach (var item in this.BindedListBox.SelectedItems)
                {
                    CategoryItem i 
= item as CategoryItem;
                    
if (i != null) list.Add(i);
                }
                
return list;
            }
        }

        
public List<Object> SelectValues
        {
            
get
            {
                List
<Object> list = new List<Object>(this.BindedListBox.SelectedItems.Count);
                
foreach (var item in this.BindedListBox.SelectedItems)
                {
                    CategoryItem i 
= item as CategoryItem;
                    
if (i != null) list.Add(i.Value);
                }
                
return list;
            }
        }

        
public List<T> GetSelectValues<T>()
        {
            List
<T> list = new List<T>(this.BindedListBox.SelectedItems.Count);
            
foreach (var item in this.BindedListBox.SelectedItems)
            {
                CategoryItem i 
= item as CategoryItem;
                
if (i != null && i.Value != null) list.Add((T)(i.Value));
            }
            
return list;
        }
    }


当我们期望某些对象或控件之间形成某种Mediator所规定的行为约束时,就new 一下这个Mediator,Bind一下,就OK了。

三、牢骚话

很不好意思的说,爬了这么多年的代码,俺还是不能理解什么是MVC、MVP,俺看不到理解这几个词对俺的代码有何帮助。俺只是看到了在现有的东东和要做的东东之间存在巨大的中间地带,这个中间地带有很多很多的重复劳动需要去消除。用扩展方法和Mediator清理中间地带后,世界清静了不少。

四、题外话

对于知识,俺觉得,还是掌握的越少越好——正应了伟人的那句话:

    知识越多越反动

当你掌握了面向对象的那些规则之后,设计模式你可以全部忘记了——那是枷锁。
当你掌握了DRY之后,面向对象的那些规则也可以全部忘记了——那是枷锁。
DRY就是Don't Repeat Yourself。用俺的话说,就是:不要复制和粘帖,那是邪恶滴。换一句话说就是,懒惰是程序员最佳的品质。
DRY是外语,不友好。“懒惰”歧义太多。还是俺的话最好理解:

对程序员来说,每一次的复制和粘帖都是在犯罪。


标签:

本站文章除注明转载外,均为本站原创或翻译。欢迎任何形式的转载,但请务必注明出处、不得修改原文相关链接,如果存在内容上的异议请邮件反馈至chenjj@evget.com

文章转载自:博客园

为你推荐

  • 推荐视频
  • 推荐活动
  • 推荐产品
  • 推荐文章
  • 慧都慧问
扫码咨询


添加微信 立即咨询

电话咨询

客服热线
023-68661681

TOP